<template>
  <div class="realm-auth-lay">
    <el-form :model="accountData" :rules="rules" ref="refForm">
      <el-form-item label="用户账号" :label-width="labelWid" prop="account">
        <el-input v-model="accountData.account" />
      </el-form-item>
      <el-form-item label="用户邮箱" :label-width="labelWid" prop="email">
        <el-input v-model="accountData.email" />
      </el-form-item>
      <el-form-item label="手机号码" :label-width="labelWid" prop="mobile">
        <el-input v-model="accountData.mobile" @input="checkMobile" />
      </el-form-item>
    </el-form>
    <div class="realm-footer">
        <el-button type="danger" @click="onCancel">取消</el-button>
        <el-button type="primary" style="margin-left: 32px;" @click="onSave">保存</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref, reactive} from "vue";
import {lookupRealmUserAccount, saveRealmUserAccount} from "@/apis";
import {useStore} from "@/stores";
import {useCurrent} from "@/utils/UseCurrentFunc";
import {msgError, msgInfo} from "@/utils/InfoUtil";

const refForm = ref();
const labelWid = ref(90);
const oldData = ref({})
const accountData = ref({})

const store = useStore();

const checkAccount = (rule: any, value: any, callback: any) => {
  const mailReg = /^[a-zA-Z0-9]+$/
  if (value) {
    if (mailReg.test(value)) {
      callback()
    } else {
      callback(new Error('请输入正确的账号'))
    }
  } else {
    callback()
  }
}

const checkEmail = (rule: any, value: any, callback: any) => {
  const mailReg = /([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
  if (value) {
    if (mailReg.test(value)) {
      callback()
    } else {
      callback(new Error('请输入正确的邮箱格式'))
    }
  } else {
    callback()
  }
};

const checkMobile = (rule: any, value: any, callback: any) => {
  const mailReg = /^1[3456789]\d{9}$/
  if (value) {
    if (mailReg.test(value)) {
      callback()
    } else {
      callback(new Error('请输入正确的手机号码'))
    }
  } else {
    callback()
  }
}

const rules = reactive({
  account: [{ required: true, message: '请输入用户账号', trigger: 'blur' },
            { validator: checkAccount, trigger: "blur" }],
  email: { validator: checkEmail, trigger: "blur" },
  mobile: { validator: checkMobile, trigger: "blur" }
})

const props = withDefaults(defineProps<{
  entry: any,
  readOnly?: any,
}>(), {});

const {current} = useCurrent(props.entry.name);

const loadUserAccount = async () => {
  const result: any = await lookupRealmUserAccount({
    userId: current().id,
    realmId: store.getCurrentRealms().id || 'default'
  });
  if (result && result.data && result.data.data) {
    result.data.data.forEach((item: any) => {
      if (item.category == 'account') {
        accountData.value.account = item.account || '';
      } else if (item.category == 'email') {
        accountData.value.email = item.account || '';
      } else if (item.category == 'mobile') {
        accountData.value.mobile = item.account || '';
      }
    })
  } else {
    accountData.value.account = '';
    accountData.value.email = '';
    accountData.value.mobile = '';
  }

  oldData.value = {...accountData.value};
}

const onCancel = () => {
  accountData.value = {...oldData.value};
}

const getAccountInfo = () => {
  const data: any = [];
  const realmId: string = store.getCurrentRealms().id || 'default';

  if (accountData.value.account) {
    data.push({
      realmId: realmId,
      category: 'account',
      account: accountData.value.account,
      data: ""
    });
  }

  if (accountData.value.mobile) {
    data.push({
      realmId: realmId,
      category: 'mobile',
      account: accountData.value.mobile,
      data: ""
    });
  }

  if (accountData.value.email) {
    data.push({
      realmId: realmId,
      category: 'email',
      account: accountData.value.email,
      data: ""
    });
  }

  return data;
}

const onSave = async () => {
  if (await refForm.value.validate()) {
    if (!accountData.value.account) {
      msgInfo('请输入用户账号')
    } else {
      const result = await saveRealmUserAccount({
        userId: current().id,
        realmId: store.getCurrentRealms().id || 'default',
        data: getAccountInfo()
      });
      if (result.code === 0) {
        msgInfo('保存账号信息成功！');
        oldData.value = {...accountData.value};
      } else {
        msgError(result.message);
      }
    }
  }
}

const refresh = () => {
  loadUserAccount();
}

onMounted(() => {

})

defineExpose({
  refresh,
})

</script>

<style scoped>
.realm-auth-lay {
    display: flex;
    flex-direction: column;
    margin: 16px 32px;
    justify-content: flex-start;
    width: 50%;
}

.inherit-item {
  display: flex;
  flex-direction: row;
  margin: 0 8px;
  justify-items: center;
  align-items: center;
}

.realm-footer {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    margin: 16px 0;
}
</style>
